package hust.iamk.backup;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.os.AsyncTask;
import android.util.Log;

public class BaseParser {
	URL url;
	List<String> listUrl;

	public BaseParser(String url) {
		// TODO Auto-generated constructor stub
		try {
			this.url = new URL(url);
			listUrl = new ArrayList<String>();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected InputStream getInputStream() {
		try {
			return url.openConnection().getInputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// Run other thread because listUrl size 0;
	public List<String> getListUrl() {
		synchronized (listUrl) {
			try {
				new AsyncTaskSax().execute().get();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return listUrl;
	}

	private class AsyncTaskSax extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			SAXParserFactory factory = SAXParserFactory.newInstance();
			try {
				SAXParser parser = factory.newSAXParser();
				SaxHandler saxHandler = new SaxHandler();
				parser.parse(getInputStream(), saxHandler);
				listUrl = saxHandler.getUrl();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
	}

}
